package com.wdb.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wdb.exception.BadRequestException;
import com.wdb.exception.EntityExistException;
import com.wdb.modules.system.domain.Job;
import com.wdb.modules.system.domain.vo.JobQueryCriteria;
import com.wdb.modules.system.mapper.JobMapper;
import com.wdb.modules.system.mapper.UserMapper;
import com.wdb.modules.system.service.JobService;
import com.wdb.utils.PageResult;
import com.wdb.utils.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/3/22 0022 14:57
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {
  private final JobMapper jobMapper;
  private final UserMapper userMapper;

  @Override
  public PageResult<Job> queryAll(JobQueryCriteria criteria, Page<Object> page) {
    return PageUtil.toPage(jobMapper.queryAll(criteria, page));
  }

  @Override
  public void create(Job job) {
    QueryWrapper<Job> jobQueryWrapper = new QueryWrapper<>();
    jobQueryWrapper.lambda().eq(Job::getName, job.getName()).ne(Job::getId, job.getId());

    List<Job> jobs = jobMapper.selectList(jobQueryWrapper);
    if (jobs.size() > 0) {
      throw new EntityExistException(Job.class, "name", job.getName());
    }
    this.save(job);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void update(Job job) {
    // 校验名称是否存在
    List<Job> jobs = jobMapper.queryExistByName(job);
    if (jobs.size() > 0) {
      throw new EntityExistException(Job.class, "name", job.getName());
    }
    // 更新数据
    this.saveOrUpdate(job);
    log.info("jobs--{}", jobs);
  }

  @Override
  public void verification(Set<Long> ids) {
    int list = userMapper.countByJobs(ids);
    if (list > 0) {
      throw new BadRequestException("已有管理用户，解除后在删除！");
    }
    this.removeBatchByIds(ids);
  }

  @Override
  public List<Job> queryAll(JobQueryCriteria criteria) {

    return jobMapper.queryAll(criteria);
  }
}
